package com.network.util;

import java.io.IOException;
import java.util.ArrayList;

public final class ByteUtil
{
	private static Long byte2long(byte bytes[], int offset, int length) throws IOException
	{
		if (bytes.length < offset)
		{
			throw new IOException("The bytes.length[" + bytes.length + "] < offset[" + offset + "]");
		}
		int iEndLoop = length;
		if (iEndLoop > (Long.SIZE / 8))
		{
			iEndLoop = (Long.SIZE / 8);
		}
		if (bytes.length < (offset + iEndLoop))
		{
			iEndLoop = bytes.length - offset;
		}
		long value = 0;
		for (int i = 0; i < iEndLoop; i++)
		{
			int intTemp = bytes[offset + i] & 0xFF;
			value = (value << 8) + intTemp;
		}
		return value;
	}

	private static void addByte(byte byteValue, ArrayList<Byte> bArray)
	{
		if (bArray.size() == 0 && byteValue == 0)
		{
			return;
		}
		bArray.add(byteValue);
	}

	public static byte[] num2byte(Number numValue, int length)
	{
		byte bytes[] = new byte[length];
		ArrayList<Byte> bArray = new ArrayList<Byte>();
		long longValue = numValue.longValue();
		for (int i = (Long.SIZE / 8 - 1); i > 0; i--)
		{
			byte byteTemp = Long.valueOf((longValue >> (i * 8))).byteValue();
			addByte(byteTemp, bArray);
		}
		byte byteTemp = Long.valueOf(longValue).byteValue();
		addByte(byteTemp, bArray);
		int zeroCount = bytes.length - bArray.size();
		for (int i = 0; i < zeroCount; i++)
		{
			bytes[i] = 0;
		}
		int start = zeroCount;
		if (start < 0)
		{
			start = 0;
		}
		for (int i = start; i < bytes.length; i++)
		{
			bytes[i] = bArray.get(i - zeroCount);
		}
		return bytes;
	}

	public static long byte2long(byte bytes[], int offset) throws IOException
	{
		return byte2long(bytes, offset, 8).longValue();
	}

	public static int byte2int(byte bytes[], int offset) throws IOException
	{
		return byte2long(bytes, offset, 4).intValue();
	}

	public static short byte2short(byte bytes[], int offset) throws IOException
	{
		return byte2long(bytes, offset, 2).shortValue();
	}
}
